<?php
defined('IN_MAIN') or exit('Invalid Access!');

function calc_next_matrix_upline_position($mid){
 global $vars;
 $db=$vars['db'];

 $result["err"]=1;
 $sql="select * from $db->users where id='$mid'";
 $rs=mysql_query($sql);
 if($rs && mysql_num_rows($rs)){
  $matrix_upline=$upline=mysql_result($rs, $i, "ref");
  $member_id=$mid;
  $cur_m_node=get_matrix_slot($matrix_upline);
  $r_new_matrix[$matrix_upline]=$cur_m_node;
  $prev_level_m_node=$cur_m_node;
  $cur_level=1;//level start from 0
  $cur_m_slot_i=1;
  $r_slot_level_node_placing_i[$cur_level]=0; //node index for placing matrix node into $r_slot
  $r_slot_level_node_checking_i[$cur_level]=1;//node index for checking previous level's all nodes are finished checked
  //loop until there is available matrix slot
  while(count($cur_m_node)>=$vars['matrix_wide']){
   if($cur_m_slot_i<=count($prev_level_m_node)){
    $matrix_upline=$prev_level_m_node[$cur_m_slot_i]["id"];
    if(!count($r_new_matrix[$matrix_upline])){
     $cur_m_node=get_matrix_slot($matrix_upline);
     $r_new_matrix[$matrix_upline]=$cur_m_node;
    }else{
     $cur_m_node=$r_new_matrix[$matrix_upline];
    }
    $cur_m_slot_i++;
    $r_slot[$cur_level][$r_slot_level_node_placing_i[$cur_level]]=$cur_m_node;
    $r_slot_level_node_placing_i[$cur_level]++;
   }else{
    $prev_level=$cur_level-1;
    if($r_slot_level_node_checking_i[$prev_level]<count($r_slot[$prev_level])){
     $prev_level_m_node=$r_slot[$prev_level][$r_slot_level_node_checking_i[$prev_level]];
     $r_slot_level_node_checking_i[$prev_level]++;
     $cur_m_slot_i=1;
    }else{
     $prev_level_m_node=$r_slot[$cur_level][0];
     $r_slot_level_node_checking_i[$cur_level]=1;
     $cur_level++;
     $r_slot_level_node_placing_i[$cur_level]=0;
     $cur_m_slot_i=1;
    }
    $matrix_upline=$prev_level_m_node[$cur_m_slot_i]["id"];
    if(!count($r_new_matrix[$matrix_upline])){
     $cur_m_node=get_matrix_slot($matrix_upline);
     $r_new_matrix[$matrix_upline]=$cur_m_node;
    }else{
     $cur_m_node=$r_new_matrix[$matrix_upline];
    }
    $cur_m_slot_i++;
    $r_slot[$cur_level][$r_slot_level_node_placing_i[$cur_level]]=$cur_m_node;
    $r_slot_level_node_placing_i[$cur_level]++;
   }
  }
  //check which slot to use
  $matrix_position=0;
  for($j=1;$j<=count($cur_m_node);$j++){
   if(!$cur_m_node[$j]){
    $matrix_position=$j;
    $j=count($cur_m_node);
   }
  }
  if(!$matrix_position){
   $matrix_position=$j;
  }
  $r_new_matrix[$matrix_upline][$matrix_position]["id"]=$member_id;
  $r_new_matrix[$matrix_upline][$matrix_position]["matrix_upline"]=$matrix_upline;
  $result["matrix_upline"]=$matrix_upline;
  $result["matrix_position"]=$matrix_position;
 }
 return $result;
}
?>